package dbUtil

import (
	"fmt"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"strconv"
	"time"
)

var myXorm *xorm.Engine

// 定义结构体(xorm支持双向映射)；如果表不存在，则会自动创建
type users struct {
	Id         int64     `xorm:"pk autoincr" json:"id"` //指定主键并自增
	UserNo     int       `xorm:"unique" json:"user_no"`
	Name       string    `json:"name"`
	Age        int       `json:"age"`
	Address    string    `json:"address"`
	CreateTime time.Time `xorm:"created" json:"create_time"`
	UpdateTime time.Time `xorm:"updated" json:"update_time"`
}

func init() {
	sqlStr := "root:rx123456@tcp(127.0.0.1:3306)/gin_demo?charset=utf8&parseTime=true&loc=Local"
	var err error

	//创建数据库引擎
	myXorm, err = xorm.NewEngine("mysql", sqlStr)
	if err != nil {
		fmt.Println("数据库连接失败:", err)
	}

	//创建或者同步表，表名称是users
	//如果数据表不存在，会根据users结构体自动创建
	err = myXorm.Sync(new(users))
	if err != nil {
		fmt.Println("数据表同步失败:", err)
	}
}

func XormGetUserList(c *gin.Context) {
	name := c.Query("name")
	var user []users
	err := myXorm.Where("name=?", name).And("age>20").Limit(10, 0).Asc("age").Find(&user)
	if err != nil {
		showError(c, fmt.Sprint(err))
		return
	}
	showSuccess(c, user)
}

func XormGetUserInfo(c *gin.Context) {
	id := c.Query("id")
	var user []users
	err := myXorm.Where("id=?", id).Find(&user)
	if err != nil {
		showError(c, fmt.Sprint(err))
		return
	}
	if len(user) == 0 {
		showSuccess(c, nil)
	}
	showSuccess(c, user[0])
}

func XormInsertData(c *gin.Context) {
	/*
		//请求参数
		{
			"user_no":1001,
			"name":"张三",
			"age":18,
			"address":"北京昌平"
		}
	*/
	var user users
	err := c.Bind(&user)
	if err != nil {
		showError(c, fmt.Sprint(err))
		return
	}
	affected, err := myXorm.Insert(user)
	if err != nil || affected <= 0 {
		fmt.Printf("insert failed, err:%v\n", err)
		showError(c, fmt.Sprint(err))
		return
	}
	showSuccess(c, "受影响的行数："+strconv.Itoa(int(affected)))
}

func XormUpdateData(c *gin.Context) {
	/*
		//请求参数
		{
		    "id":1,
		    "age":13,
		    "address":"河北"
		}
	*/
	var u users
	err := c.Bind(&u)
	if err != nil {
		showError(c, fmt.Sprint(err))
		return
	}

	//先查找
	var user []users
	err = myXorm.Where("id=?", u.Id).Find(&user)
	//fmt.Println(myXorm.NewSession().LastSQL())
	if err != nil {
		showError(c, fmt.Sprint(err))
		return
	}
	if len(user) == 0 {
		showError(c, "数据不存在")
		return
	}

	//再修改
	affected, err := myXorm.Where("id=?", u.Id).Update(&users{
		Age:     u.Age,
		Address: u.Address,
	})
	if err != nil {
		showError(c, fmt.Sprint(err))
		return
	}
	showSuccess(c, "受影响的行数："+strconv.Itoa(int(affected)))
}

func XormDeleteData(c *gin.Context) {
	id := c.Query("id")
	//先查找
	var user []users
	err := myXorm.Where("id=?", id).Find(&user)
	if err != nil {
		showError(c, fmt.Sprint(err))
		return
	}
	if len(user) == 0 {
		showError(c, "数据不存在")
		return
	}

	//再删除
	affected, err := myXorm.Where("id=?", id).Delete(&users{})
	if err != nil {
		showError(c, fmt.Sprint(err))
		return
	}
	showSuccess(c, "受影响的行数："+strconv.Itoa(int(affected)))
}
